package com.example.sensors;

import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.example.singletones.contextObj;

public class Sensor_Battery extends AbstractSensor {
	public static final String NAME = "BATTERY";
	private static int batteryLevel = -1;
	private Sensor_Battery_Helper mSensor_Battery_Helper = new Sensor_Battery_Helper();

	private class Sensor_Battery_Helper extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Sensor_Battery.this.onReceive(context, intent);
		}
	}

	public Sensor_Battery() {
	}

	public int batteryStates(int battery) {
		if (battery == 100) {
			return 100;
		}
		if (battery < 100 && battery >= 75) {
			return 75;
		}
		if (battery < 75 && battery >= 50) {
			return 75;
		}
		if (battery < 50 && battery >= 25) {
			return 25;
		}
		if (battery < 25 && battery >= 10) {
			return 10;
		}
		if (battery < 10) {
			return battery;
		}
		return -1;
	}

	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		int tBatteryLevel = intent.getIntExtra("level", 0);
		tBatteryLevel = batteryStates(tBatteryLevel);
		if (tBatteryLevel != -1 && tBatteryLevel != batteryLevel) {
			batteryLevel = tBatteryLevel;
			Map<String, Object> eventArgs = initEventArgs();
			eventArgs.put("eventType", "sensorInfoReceived");
			eventArgs.put("batteryLevel", "" + batteryLevel);
			OnSensorChanged(eventArgs);
		}
	}

	public void disableSensor() {
		super.disableSensor();
		contextObj.getInstance().getmContext()
				.unregisterReceiver(mSensor_Battery_Helper);
	}

	public void enableSensor() {
		super.enableSensor();
		contextObj
				.getInstance()
				.getmContext()
				.registerReceiver(mSensor_Battery_Helper,
						new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
	}

	public String getSensorName() {
		return NAME;
	}
}
